//
//  WDHeader.m
//  WDPolymerizeSDK
//
//  Created by little People on 2023/5/30.
//

#import "WDHeader.h"
#import "WDSplashManager.h"
#import "WDNativeManager.h"
#import "WDAdStatusManager.h"
#import "WDIronSourceManager.h"
#import "WDRewardedVideoManager.h"
#import "WDInterstitialManager.h"
#import "WDBannerManager.h"
#import "WDBMSManager.h"
#import "WDBMSModel.h"
#import "WDKeychain.h"
#import "WDADControlManager.h"
#import "WDNSLog.h"
#import "WDADOrderManager.h"
#import "WDCardManager.h"
#import "WDCardZDYManager.h"
#import "WDDefaultSysFunctionManager.h"
#import "WDCardView.h"
#import "WDCustomManager.h"
#import "WDNativeViewController.h"
#import "WDFBManager.h"
#import "WDAdjustManager.h"
#import "WDCallBackModel.h"
#import "WDThinkingManager.h"
#import "WDFirebaseManager.h"
#import "WDFirebaseManager.h"
#import "WDInAppPurchaseManager.h"
#import "WDJsonManager.h"
#import "WDInAppPurchaseHandleManager.h"
#import "WDCallBack.h"
#import "WDKeychain.h"
#import "WDCustomCardModel.h"
#import "WDADManager.h"
#import "WDOrientationManager.h"
#import <IronSource/IronSource.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/AdSupport.h>
#import <UIKit/UIKit.h>
#import <JJException/JJException.h>
#import <AppLovinSDK/AppLovinSDK.h>

@import GoogleMobileAds;;
@interface WDHeader ()<WDSplashManagerDelegate>
@property (nonatomic, assign)BOOL adFirstShow;
@property (nonatomic, assign)UIInterfaceOrientationMask currentDeviceOrientation;
@end
@implementation WDHeader
static WDHeader *_header = nil;
+ (instancetype)shareHeader
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _header = [[self alloc] init];
        
    });
    return _header;
}

- (void)WDStartAdmob
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
        if (@available(iOS 14, *)) {
            [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
                
                switch (status) {
                    case ATTrackingManagerAuthorizationStatusDenied:
                        //用户拒绝IDFA
                        WDLog(@"用户拒绝IDFA");
                        break;
                    case ATTrackingManagerAuthorizationStatusAuthorized:{
                        //用户允许IDFA
                        if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
                            NSString *idfaString = [[ASIdentifierManager sharedManager] advertisingIdentifier].UUIDString;
                            WDLog(@"用户允许IDFA:%@",idfaString);
                        }
                    }
                        break;
                    case ATTrackingManagerAuthorizationStatusNotDetermined: {
                        WDLog(@"用户未做选择或未弹窗IDFA");
                        //用户未做选择或未弹窗IDFA
                        //请求弹出用户授权框，只会在程序运行是弹框1次，除非卸载app重装，通地图、相机等权限弹框一样
                        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
                            if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
                                // 你的操作
                            }
                            
                        }];
                    }
                        break;
                    default:
                        break;
                }
                
                
            }];
        } else {
            // Fallback on earlier versions
        }
            
    });
    
    
    
}

- (void)WDLogEnable:(BOOL)flag
{
    [WDNSLog setLogEnable:flag];
}

- (void)WDShowSplashAdWithHasRemove:(BOOL)remove
{
//    if ([WDADManager shareADManager].WDADShowStats == ADShowing)
//    {
//        return;
//    }
    
    [WDCallBackModel shareCallBackModel].adSpace = splash;
    //先请求bms参数
    if (![WDBMSModel shareBMSModel].hasBMSContent)
    {
        [WDBMSManager WDGetWithVersion:@"" appName:@"" completionHandler:^(BOOL isSuccess, WDBMSModel * _Nonnull model) {
            if (isSuccess && model)
            {
//                [[WDCardZDYManager shareCardZDYManager] loadZDYCard];
                if (![[WDADControlManager shareADControlManager] canShowSplash])
                {
                    return;
                }
                
                [[WDAdStatusManager shareStatusManager] adRequestWithEventName:SPLASH_EVENT_NAME];
                if (remove)
                {
                    return;
                }
                if (!self.adFirstShow)
                {
                    //请求开屏广告
                    [[WDSplashManager shareSplash] requestAppOpenAd];
                    //顺便加载一下NativeAd
                    [[WDNativeManager shareNative] loadNativeAd];
                }
                else
                {
                    
                    [[WDSplashManager shareSplash] tryToPresentAd];
                }
            }else{
//                [self WDShowSplashAdWithHasRemove:NO];
            }
        }];
    }else{
        if (![[WDADControlManager shareADControlManager] canShowSplash])
        {
            return;
        }
        
        [[WDAdStatusManager shareStatusManager] adRequestWithEventName:SPLASH_EVENT_NAME];
        if (remove)
        {
            return;
        }
        if (!self.adFirstShow)
        {
            [[WDSplashManager shareSplash] requestAppOpenAd];
        }
        else
        {
            [[WDSplashManager shareSplash] tryToPresentAd];
        }
    }
    
}

- (void)WDRemoveAd
{
//    [WDKeychain WDKeychainSaveSplashOpenStatus:@"1"];
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"WDRemoveAd"];
}

- (NSString *)WDGetRemoveAdStats
{
    NSString *ad = [[NSUserDefaults standardUserDefaults] objectForKey:@"WDRemoveAd"];
//    return [WDKeychain WDKeychainGetSplashOpenStatus];
    return ad?ad:@"";
}

- (void)WDShowNativeAd
{
    if ([WDADManager shareADManager].WDADShowStats == ADShowing)
    {
        return;
    }
    [WDADManager shareADManager].WDADShowStats = ADShowing;
    
    [WDCallBackModel shareCallBackModel].adSpace = native;
    [[WDNativeManager shareNative] showNativeAd:NO isJsonSource:NO];
}

- (void)WDShowRewardedVideo
{
    
    [[WDRewardedVideoManager shareRewardedVideoManager] showIrSourceRV];
}

- (void)WDShowInterstitial
{
//    if ([WDADManager shareADManager].WDADShowStats == ADShowing)
//    {
//        return;
//    }
    
    [WDADManager shareADManager].WDADShowStats = ADShowing;
    [WDCallBackModel shareCallBackModel].adSpace = inter;
    [WDCustomManager shareCustomManager].customCout = 5;
    if ([[WDADControlManager shareADControlManager] canShowInterstitial])
    {
//        [[WDInterstitialManager shareInterstitialManager] showInterstitial];
        if (![[WDADOrderManager shareOrderManager] adOrderWithList:[WDBMSModel shareBMSModel].interList isCardAd:NO])
        {
//            [IronSource loadInterstitial];
            [[WDInterstitialManager shareInterstitialManager] showInterstitial];
        }

        else
        {
            [WDADManager shareADManager].WDADShowStats = ADNone;
        }
        
    }
    else
    {
        [WDADManager shareADManager].WDADShowStats = ADNone;
    }
    
}

- (void)WDShowBanner
{
//    if ([WDADManager shareADManager].WDADShowStats == ADShowing)
//    {
//        return;
//    }
//    [WDADManager shareADManager].WDADShowStats = ADShowing;
    
//    [WDCallBackModel shareCallBackModel].adSpace = banner;
    [[WDBannerManager shareBannerManager] showBanner];
}

- (void)WDCloseBanner
{
    [[WDBannerManager shareBannerManager] closeBanner];
}

- (void)WDBannerDirectionWithTop:(BOOL)topDir

{
    [[WDBannerManager shareBannerManager] setBannerDirectionWithTop:topDir];
}

- (void)WDShowCardWithSize:(WCardAdSize)WCardAdSize leftMargin:(int)leftMargin topMargin:(int)topMargin rightMargin:(int)rightMargin bottomMargin:(int)bottomMargin
{
    if ([WDADManager shareADManager].WDADShowStats == ADShowing)
    {
        return;
    }
    [WDADManager shareADManager].WDADShowStats = ADShowing;
    
    if ([[WDADControlManager shareADControlManager] canShowCard])
    {
        [WDCardModel shareCardModel].size = WCardAdSize;
        [WDCardModel shareCardModel].leftMargin = leftMargin;
        [WDCardModel shareCardModel].topMargin = topMargin;
        [WDCardModel shareCardModel].rightMargin = rightMargin;
        [WDCardModel shareCardModel].bottomMargin = bottomMargin;
        
        [WDCallBackModel shareCallBackModel].adSpace = card;
        if (![[WDADOrderManager shareOrderManager] adOrderWithList:[WDBMSModel shareBMSModel].cardList isCardAd:YES])
        {
            [[WDNativeManager shareNative] loadNativeAd];
            [WDNativeManager shareNative].adLoaderCallBackBlcok = ^{
                [[WDCardZDYManager shareCardZDYManager] showCardViewIsCustom:NO];
            };
        }
    }
    
    
    
    
}

//显示广告测试面板
- (void)WDShowTestAD{
    
//    NSArray *windows = [UIApplication sharedApplication].windows;
//    UIWindow *window = windows[0];
//
//    if (window) {
//        [IronSource launchTestSuite:window.rootViewController];
//    }
    [[ALSdk shared] showMediationDebugger];

}



- (void)WDHideCard
{
    [[WDCardZDYManager shareCardZDYManager] hideCardView];
}

- (void)WDSysShareWithTitle:(NSString *)title url:(NSString *)url
{
    [[WDDefaultSysFunctionManager shareSysFunctionManager] sysShareFunctionWithTitle:title url:url];
}

- (void)WDSysScore
{
    [[WDDefaultSysFunctionManager shareSysFunctionManager] sysScore];
}

- (void)WDSysVibrate:(BOOL)repeat
{
    [[WDDefaultSysFunctionManager shareSysFunctionManager] sysVibrate:repeat];
}

- (void)WDSysCancelVibrate
{
    [[WDDefaultSysFunctionManager shareSysFunctionManager] cancelVibrate];
}

- (void)WDShowCustom
{
    
    [[WDCustomManager shareCustomManager] showCustomAd];
}

- (void)WDFBLogin
{
    [[WDFBManager shareFBManager] FBLogin];
}

- (void)WDFBLogout
{
    [[WDFBManager shareFBManager] FBLogOut];
}

- (void)WDFBShareWithTitle:(NSString *)title url:(NSString *)url content:(NSString *)shareContent
{
    [[WDFBManager shareFBManager] FBShareWithTitle:title url:url content:shareContent];
}

- (void)WDApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
   [JJException configExceptionCategory:JJExceptionGuardAll];
   [JJException startGuardException];

    [[WDAdjustManager shareAdjustManager] adjustConfig];
    [[WDThinkingManager shareThinkingManager] thinkingConfig];
//     [[WDInAppPurchaseManager shareInAppPurchaseManager] requestProductLists:[WDJsonManager productIdListForSDKConfigFile]];
    [WDOrientationManager shareOrientationManager].currentDeviceOrientation = [self deviceOrientation];
    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"WDOrientation"];
    self.currentDeviceOrientation = [self deviceOrientation];

    [WDSplashManager shareSplash].delegate = self;
    
    // Tracking authorization completed. Start loading ads here.
    [GADMobileAds.sharedInstance startWithCompletionHandler:nil];
//            [[WDNativeManager shareNative] loadNativeAd];
    
    [[WDFBManager shareFBManager] FBApplication:application didFinishLaunchingWithOptions:launchOptions];
    [[WDFirebaseManager shareFirebaseManager] firebaseRegisterForRemoteNotificationsApplication:application];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([WDBMSModel shareBMSModel].hasBMSContent){
            if ([[NSString stringWithFormat:@"%@",[WDBMSModel shareBMSModel].GM] isEqualToString:@"1"]) {
                [[WDHeader shareHeader] WDLogEnable:YES];
            }
            
        }
        [[WDIronSourceManager shareIronSourceManager] initIronSource];
    });
    


}

- (void)WDApplication:(UIApplication *)application
            openURL:(NSURL *)url
            options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    [[WDFBManager shareFBManager] FBApplication:application openURL:url options:options];
}

- (void)WDAdjustCallBackHandler:(void (^)(BOOL success))handler
{
    [WDAdjustManager shareAdjustManager].adjustCallBackBlcok = ^(BOOL isSuccess) {
        handler(isSuccess);
    };
    [[WDAdjustManager shareAdjustManager] adjustConfig];
}

- (NSString *)WDGetAdjustCampaign
{
    NSString *adjustCampaign = [[NSUserDefaults standardUserDefaults] objectForKey:@"w_campaign"];
    if (adjustCampaign <= 0 || !adjustCampaign) {
        return @"organic";
    }
    return adjustCampaign;
}

- (NSString *)WDGetAdjustCreative
{
    NSString *adjustCreative = [[NSUserDefaults standardUserDefaults] objectForKey:@"w_creative"];
    if (adjustCreative <= 0 || !adjustCreative) {
        return @"organic";
    }
    return adjustCreative;
}

- (NSString *)WDGetUUID
{
    return [WDKeychain WDKeychainGetUUID];
}

- (void)WDAdjustEvent:(ADJEvent *)event
{
    [[WDAdjustManager shareAdjustManager] adjustEvent:event];
}

- (void)WDTrackUserProperty:(id)json
{
    [[WDThinkingManager shareThinkingManager] thinkingTrackUserProperty:json];
}

- (void)WDThinkingTrackEventWithKey:(NSString *)key jsonStr:(NSString *)jsonStr
{
    [[WDThinkingManager shareThinkingManager] thinkingTrackEventWithKey:key jsonStr:jsonStr];
}
- (void)WDThinkingSetSuperPropertiesJsonStr:(NSString *)jsonStr{
    
    [[WDThinkingManager shareThinkingManager] thinkingSetSuperPropertiesJsonStr:jsonStr];
}

- (void)WDThinkingTrackLevelEnter:(NSInteger)level
{
    [[WDThinkingManager shareThinkingManager] thinkingTrackLevelEnter:level];
}

- (void)WDThinkingTrackLevelStart:(NSInteger)level
{
    [[WDThinkingManager shareThinkingManager] thinkingTrackLevelStart:level];
}

- (void)WDThinkingTrackLevelWin:(NSInteger)level
{
    [[WDThinkingManager shareThinkingManager] thinkingTrackLevelWin:level];
}

- (void)WDThinkingTrackLevelFail:(NSInteger)level
{
    [[WDThinkingManager shareThinkingManager] thinkingTrackLevelFail:level];
}

- (void)WDThinkingTrackLevelRevive:(NSInteger)level
{
    [[WDThinkingManager shareThinkingManager] thinkingTrackLevelRevive:level];
}

- (void)WDThinkingTrackLevelRetry:(NSInteger)level
{
    [[WDThinkingManager shareThinkingManager] thinkingTrackLevelRetry:level];
}

- (void)WDThinkingTrackLevelProp:(NSInteger)level
{
    [[WDThinkingManager shareThinkingManager] thinkingTrackLevelProp:level];
}

- (void)WDRequestFCMToken
{
    [[WDFirebaseManager shareFirebaseManager] firebaseRequestFCMToken];
}

- (void)WDFirebaseApnsToken:(NSDate *)token
{
    [[WDFirebaseManager shareFirebaseManager] firebaseApnsToken:token];
}

- (void)WDLaunchInAppPurchase:(NSString *)productId
{
    [[WDInAppPurchaseManager shareInAppPurchaseManager] launchInAppPurchase:productId];
}

- (void)WDRestoreInAppPurchase:(NSString *)productId
{
    [[WDInAppPurchaseManager shareInAppPurchaseManager] restoreInAppPurchase:productId];
}

- (void)WDRequestProductLists
{
    
    [[WDInAppPurchaseManager shareInAppPurchaseManager] requestProductLists:[WDJsonManager productIdListForSDKConfigFile]];
    if ([WDCallBack shareCallBack].onProductListCallBack)
    {
        [WDCallBack shareCallBack].onProductListCallBack([WDInAppPurchaseHandleManager shareInAppPurchaseHandleManager].productIds);
    }
}

- (NSDictionary *)WDGetBMSContent
{
    return [WDBMSModel shareBMSModel].dataDict;
}

- (UIInterfaceOrientationMask)WDDeviceSupportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    NSString *orientation = [[NSUserDefaults standardUserDefaults] objectForKey:@"WDOrientation"];
    if ([orientation isEqualToString:@"1"])
    {
        return UIInterfaceOrientationMaskPortrait;
        
    }
    if ([orientation isEqualToString:@"2"])
    {
        return UIInterfaceOrientationMaskAll;
        
    }
//    if ([orientation isEqualToString:@"3"])
//    {
////        return self.currentDeviceOrientation;
//        return UIInterfaceOrientationMaskAll;
//    }
    return self.currentDeviceOrientation;

    
}

- (UIInterfaceOrientationMask)deviceOrientation
{
    UIInterfaceOrientation dori = [UIApplication sharedApplication].statusBarOrientation;
    if (dori == UIInterfaceOrientationLandscapeLeft){
        return UIInterfaceOrientationMaskLandscapeLeft;
    }
    else if (dori == UIInterfaceOrientationLandscapeRight){
        return UIInterfaceOrientationMaskLandscapeRight;
    }
    else if (dori == UIInterfaceOrientationPortraitUpsideDown){
        return UIInterfaceOrientationMaskPortraitUpsideDown;
    }
    return UIInterfaceOrientationMaskPortrait;
}

#pragma mark WDSplashManagerDelegate
- (void)adLoadedSuccessfully
{
    if (!self.adFirstShow)
    {
        self.adFirstShow = YES;
        [[WDSplashManager shareSplash] tryToPresentAd];
    }
    
}

@end
